package at.technikum.fotoalbum.beans;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.myfaces.custom.fileupload.UploadedFile;

import at.technikum.fotoalbum.database.DatabaseConnector;
import at.technikum.fotoalbum.utils.Thumbnail;
import at.technikum.fotoalbum.utils.Utils;

public class FileUploadBean {
	private static final Log log = LogFactory.getLog(FileUploadBean.class);
	private UploadedFile upFile;
	FileOutputStream out;
	InputStream stream;
	String path;
	String pictureName;

	public String getPictureName() {
		return pictureName;
	}

	public void setPictureName(String pictureName) {
		this.pictureName = pictureName;
	}

	public FileUploadBean() {
	}

	public UploadedFile getUpFile() {
		return upFile;
	}

	public void setUpFile(UploadedFile upFile) {
		this.upFile = upFile;
	}

	public String upload() throws IOException {
		try {
			stream = upFile.getInputStream();
			long size = upFile.getSize();
			byte[] buffer = new byte[(int) size];
			stream.read(buffer, 0, (int) size);
			// change this to your path to resources/pictures
			path = "/home/ande/ws/fotoalbum/bilderalbum/WebContent/resources/pictures/";
			out = new FileOutputStream(path + upFile.getName());
			out.write(buffer);
			log.info("FileUploadBean: File Upload successfully.");
		} catch (Exception ioe) {
			log.error("FileUploadBean: File Upload unsuccesfully. " + ioe.toString());
			return "no";
		} finally {
			if (stream != null) {
				stream.close();
			}
			if (out != null) {
				out.close();
			}
		}
		Thumbnail tn = new Thumbnail(path + upFile.getName(), path
				+ "thumbnail_" + upFile.getName(), 100, 100, 100);
		tn.generateThumImage();
		DatabaseConnector dc = (DatabaseConnector) Utils.getManagedBean("databaseConnector");
		SessionBean sb = (SessionBean) Utils.getManagedBean("sessionBean");
		dc.createImage(new Image(pictureName, "/resources/pictures/" + upFile.getName(), upFile.getName(), new java.sql.Date((new java.util.Date()).getTime())), sb.getNick());
		pictureName = "";
		return "/pages/userPicturesUpload";

	}
}
